package site.zbox.tool.swing;

import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;

import javax.swing.JComponent;

import site.zbox.tool.lang.StringUtils;
import site.zbox.tool.lang.Version;

@Version("2021.08.04")
public class ComponentMap {
    private Map<String, JComponent> componentMap = new TreeMap<>();
    private Map<String, Map<String, String>> dataMap = new TreeMap<>();

    public Set<String> idSet() {
        return new TreeSet<>(componentMap.keySet());
    }

    @SuppressWarnings("unchecked")
    public <T> T getComponent(String id) {
        id = StringUtils.defaultString(id);
        return (T) componentMap.get(id);
    }

    public <T extends JComponent> T setComponent(String id, final T component) {
        id = StringUtils.defaultString(id);
        componentMap.put(id, component);
        return component;
    }

    public Map<String, String> setData(final String id, Map<String, String> data) {
        final Map<String, String> temp = getData(id);
        if (data != null) {
            temp.putAll(data);
        }
        return temp;
    }

    public Map<String, String> getData(String id) {
        id = StringUtils.defaultString(id);
        Map<String, String> data = dataMap.get(id);
        if (data == null) {
            data = new TreeMap<>();
            dataMap.put(id, data);
        }
        return data;
    }

    public <T extends JComponent> T setComponent(final String id, final T component, final Map<String, String> data) {
        setData(id, data);
        return setComponent(id, component);
    }
}
